import { login as _login, logout as _logout, currentUser } from "@/api/user.js";
import { removeToken, removeInfo } from "@/utils/auth";
import { resetRouter } from "@/router";
const loginPubkey =
    "046576e3722a163b53b5b2c3e8211514097c5dda8d1bb4f6ded55cbb08755f78b833d449f388af22785f55b431562de49e08e248cbf47794cfed45cc8c7ef5799a";
const state = {
    roles: null,
    routes: []
};

const actions = {
    // user login
    login({ commit }, userInfo) {
        const { username, password, code } = userInfo;
        return _login({
            userAccount: username.trim(),
            credential: sm2Encrypt(password, loginPubkey, 0),
            userTypes: ["admin", "agent","channelBusiness"],
            type: "username",
            deviceType: "admin",
            code
        });
    },

    getInfo({ commit, state }) {
        if (state.currentUser) return state.currentUser;
        return currentUser().then(data => {
            return data;
        });
    },

    logout({ commit, state, dispatch }) {
        return new Promise((resolve, reject) => {
            _logout(state.token)
                .then(() => {
                    removeToken();
                    resetRouter();
                    removeInfo();
                    dispatch("tagsView/delAllViews", null, { root: true });
                    resolve();
                })
                .catch(error => {
                    reject(error);
                });
        });
    },

    resetToken({ commit }) {
        return new Promise(resolve => {
            removeToken();
            resolve();
        });
    }
};

export default {
    namespaced: true,
    state,
    actions
};
